import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class StartServer {
    public static void main(String[] args) throws Exception {
        String port="8888";
        if(args.length!=0)
            port=args[0];
        ServerSocket server = new ServerSocket(Integer.parseInt(port));
        System.out.println("服务器启动了...");

        while (true) {
            Socket accept = server.accept();
            new Thread(new MyRunnable(accept)).start();
        }
    }

    public static class MyRunnable implements Runnable {
        Socket socket;
        Response resp;
        Request req;

        //构造函数
        public MyRunnable(Socket socket) {
            this.socket = socket;
            try {
                Session session = new Session();
                resp = new Response(socket.getOutputStream(),session);
                req = new Request(socket.getInputStream(),session);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            String url = req.getUrl();
            System.out.println("url " + url);

            try {
                List<Filter> filters = FilterFactory.getFilters();
                for (Filter filter : filters) {
                    filter.doFilter(req,resp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            //如果请求是  html  jpg gif结尾    或者是文件目录   直接返回
            try {
                String path = url.substring(1);//  得到路劲xxx/yyy
                System.out.println("path " + path);

                File file = new File(path);
                if (path.equals("")) {
                    file = new File("WebContent");
                }
                if (file.isDirectory()) {

                    OutputStream outputStream = socket.getOutputStream();
                    outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                    outputStream.write("Content‐Type:text/html\r\n".getBytes());
                    outputStream.write("\r\n".getBytes());
                    String[] list = file.list();
                    String str = "";
                    for (String s : list) {
                        str += ("<a href=\"WebContent/"+s+"\">"+s + "</a><br>");
                    }
                    System.out.println(str);
                    outputStream.write(str.getBytes());
                    outputStream.close();
                    return;
                }
                if (url.endsWith("jpg") || url.endsWith("html") || url.endsWith("gif")) {
                    FileInputStream fis = new FileInputStream(path);//从文件里读取
                    OutputStream out = socket.getOutputStream();
                    byte[] bytes = new byte[1024];
                    int len;

                    out.write("HTTP/1.1 200 OK\r\n".getBytes());
                    out.write("Content‐Type:text/html\r\n".getBytes());
                    out.write("\r\n".getBytes());
                    while ((len = fis.read(bytes)) != -1)//从文件里读取然后写出
                    {
                        out.write(bytes, 0, len);
                    }
                    System.out.println("本次请求处理结束...");
                    out.close();
                    fis.close();
                    socket.close();
                    return;
                }
            } catch (IOException e) {
                System.out.println(e);
            }

            if (url.endsWith("jsp")) {
                try {
                    System.out.println("jsp::" + url);
                    String jspPath = url.substring(1);
                    //url-pattern为/mx的映射类为jspServlet专门处理所有jsp请求
                    //id为jspServlet     对应路径为/mx        对应类为JspServlet
                    JspServlet jspServlet = (JspServlet) ServletFactory.getServlet("/mx");
                    jspServlet.setPath(jspPath);
                    if (req.getMethod().equalsIgnoreCase("get"))
                        jspServlet.doGet(req, resp);
                    else if ((req.getMethod().equalsIgnoreCase("post")))
                        jspServlet.doPost(req, resp);

                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }

            //既不是目录  不是html  不是jpg  不是gif    此时调用servlet
            //根据url调用相应的servlet
            Servlet servlet = null;
            try {
                servlet = ServletFactory.getServlet(url);
                if (servlet == null) {
                    resp.setCode(200);
                    resp.print("<html lang=\"zh-CN\"><head>\n" +
                            "<meta charset=\"utf-8\"></head><h1>404页面找不到啊</h1></html>");
                    socket.close();
                    return;
                }
                if (req.getMethod().equalsIgnoreCase("get"))
                    servlet.doGet(req, resp);
                else if ((req.getMethod().equalsIgnoreCase("post")))
                    servlet.doPost(req, resp);

                //关闭连接   否则页面就算加载完成也一直转
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
